﻿var tryTime, timeout, randomMin, randomMax, coursewareId, coursewareName;
var validHandle, randomHandle, learningHandle,
    currentTryTime, currentTimeout, currentRandomValue, currentRandomTotal, totals = 0;
var studentValidate;
var validTotals = 0;
function validInterval() {
    currentTimeout--;
    if (currentTimeout <= 0) {
        stopValidInterval();
        $.closeModal();
        $('#b_signout').remove();
        $("#totalTime").html('00:00:00');
        totals = 0;
        showVideo();
        $.alert('您已超过验证时间，学习将不计时。');
    } else {
        $('#validate_vtitle').html(currentTimeout);
    }
};

function startValidInterval() {
    if (!validHandle) {
        stopRandomInterval();
        currentTryTime = tryTime;
        currentTimeout = timeout;
        validHandle = window.setInterval(function () { validInterval(); }, 1000);
    }
};

function stopValidInterval() {
    if (validHandle) {
        window.clearInterval(validHandle);
        validHandle = null;
    }
};

function valid(validType, callback) {

    hideVideo();
    var choose = function (answer) {
        $.showIndicator();
        var validateId = studentValidate.id;
        $.ajax({
            url: '/StudentLearning/LearningValidate',
            method: 'post',
            data: {
                validateId: validateId,
                coursewareId: coursewareId,
                answer: answer,
                validTotals: validTotals,
                recordType: validType
            },
            success: function (result) {
                $.hideIndicator();
                if (result.success) {
                    $.closeModal();
                    stopValidInterval();
                    if (callback) {
                        callback();
                    }
                    validTotals = 0;
                    showVideo();
                } else {
                    currentTryTime--;
                    if (currentTryTime <= 0) {
                        stopValidInterval();
                        $.closeModal();
                        $('#b_signout').remove();
                        $("#totalTime").html('00:00:00');
                        totals = 0;
                        showVideo();
                        $.alert('回答问题达到最大次数,学习将不计时！');
                    } else {
                        $.closeModal();
                        valid(validType, callback);
                    }
                }
            }
        });
    };

    $.ajax({
        url: '/StudentLearning/LearningValidateModal',
        method: 'post',
        success: function (result) {
            studentValidate = result;
            var vbtns = [];
            $.each(result.options, function (i, v) {
                vbtns.push({
                    text: v,
                    onClick: function () {
                        choose(v);
                    }
                });
            });

            $.modal({
                title: '学习验证(剩余<span id="validate_vtitle" style="color:red;"></span>秒)',
                text: '<img src="/StudentLearning/ValidateImage?validateId=' + result.id + '">',
                verticalButtons: true,
                buttons: vbtns
            });
            startValidInterval();
        }
    });
};

function removeVideo() {
    if ($('video').length == 0) {
        return;
    }
    var player = new MediaElementPlayer('video');
    player.pause();
    player.container.remove();
}

function hideVideo() {
    if ($('video').length == 0) {
        return;
    }
    var player = new MediaElementPlayer('video');
    player.pause();
    player.container.hide();
}

function showVideo() {
    if ($('video').length == 0) {
        return;
    }
    var player = new MediaElementPlayer('video');
    player.play();
    player.container.show();
}


function getRandomNumber(min, max) {
    return parseInt(Math.random() * (max - min + 1) + min);
};

function randomInterval(callback) {
    if (currentRandomValue >= currentRandomTotal) {
        stopRandomInterval();
        stopLearningInterval();
        valid(3, callback);
    } else {
        currentRandomValue++;
    }
}

function startRandomInterval(callback) {
    if (!randomHandle) {
        currentRandomTotal = getRandomNumber(randomMin, randomMax);
        currentRandomValue = 0;
//        console.log(currentRandomTotal);
        randomHandle = window.setInterval(function () { randomInterval(callback); }, 1000);
    }
}

function stopRandomInterval() {
    if (randomHandle) {
        window.clearInterval(randomHandle);
        randomHandle = null;
    }
}



function learningInterval() {
    totals += 1;
    validTotals += 1;

    var _tos = totals;
    var hour = Math.floor(_tos / 3600);
    if (hour < 1) {
        hour = 0;
    }
    _tos = _tos - (hour * 3600);
    var min = Math.floor(_tos / 60);
    if (min < 1) {
        min = 0;
    }
    _tos = _tos - (min * 60);
    var sec = _tos % 60; // 这是取模

    if (hour < 10) {
        hour = '0' + hour;
    }

    if (min < 10) {
        min = '0' + min;
    }

    if (sec < 10) {
        sec = '0' + sec;
    }

    $("#totalTime").html(hour + ':' + min + ':' + sec);
}

function startLearningInterval() {
    if (!learningHandle) {
        learningHandle = window.setInterval(function () { learningInterval(); }, 1000);
        startRandomInterval(function () {
            startLearningInterval();
        });
    }
}

function stopLearningInterval() {
    if (learningHandle) {
        window.clearInterval(learningHandle);
        learningHandle = null;
    }
}


function begin() {
    $.ajax({
        masked: false,
        url: '/StudentLearning/Begin',
        method: 'post',
        data: { coursewareId: coursewareId },
        success: function (result) {
            if (result.success) {
                startLearningInterval();
            } else {
                $.alert(result.message);
            }
        }
    });
}

function commit() {
    removeVideo();
    var period = validTotals;
    $.ajax({
        method: 'post',
        url: '/StudentLearning/Commit',
        data: { period: period },
        success: function (result) {
            if (result.success) {
                $.alert('学时保存成功！', function (i) {
                    window.location.href = '/default/index';
                });
            } else {
                $.alert(result.message);
            }
        }
    });
}

function checkPeriod() {
    $.showIndicator();
    $.ajax({
        url: '/StudentLearning/CheckPeriod',
        method: 'post',
        data: { coursewareId: coursewareId },
        success: function (result) {
            $.hideIndicator();
            if (result.success) {
                valid(1, begin);
            } else {
                $('#b_signout').remove();
                //$.alert(result.message);
                $('#totalTime').html(result.message);
            }
        }
    });
}


function init(p_tryTime, p_timeout, p_randomMin, p_randomMax, p_coursewareId, p_coursewareName) {
    tryTime = p_tryTime;
    timeout = p_timeout;
    randomMin = p_randomMin;
    randomMax = p_randomMax;
    coursewareId = p_coursewareId;
    coursewareName = p_coursewareName;

    $(function () {

        $('#b_signout').click(function () {
            stopLearningInterval();
            valid(2, commit);
        });

        checkPeriod();
    });
}
